1806C - Sequence Master - CodeForces Solution


brute force constructive algorithms math

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define int long long

const int maxn = 2e5+8, inf = 1e18+9, mod = 1e9+7;

void solve() {
    int n; cin >> n;
    vector<int> a(n * 2 + 1);
    for (int i = 1; i <= n * 2; i++) cin >> a[i];
    sort(a.begin() + 1, a.end());
    if (n == 1) return (void)(cout << a[2] - a[1] << endl);
    int ans = 0, res = 0;
    for (int i = 1; i <= n * 2; i++) ans += llabs(a[i]);
    if (n % 2 == 0) {
        for (int i = 1; i <= n * 2; i++) {
            if (i != n * 2) res += llabs(a[i] + 1);
            else res += llabs(a[i] - n);
        }
        ans = min(ans, res); res = 0;
    }
    if (n == 2) {
        for (int i = 1; i <= n * 2; i++) res += llabs(a[i] - 2);
        ans = min(ans, res);
    }
    cout << ans << endl;
}

signed main() {
    cin.tie(0)->sync_with_stdio(false), cout << fixed << setprecision(15);
    int t = 1; cin >> t;
    while (t--) solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest
727C - Guess the Array
1625C - Road Optimization
1715D - 2+ doors
267A - Subtractions
1582A - Luntik and Concerts
560A - Currency System in Geraldion
946A - Partition
1068B - LCM
1692E - Binary Deque
679A - Bear and Prime 100
488A - Giga Tower
14A - Letter
1150A - Stock Arbitraging
1552A - Subsequence Permutation
1131F - Asya And Kittens
1475F - Unusual Matrix
133B - Unary
1547A - Shortest Path with Obstacle
624A - Save Luke
1238A - Prime Subtraction
1107C - Brutality
1391B - Fix You
988B - Substrings Sort
312A - Whose sentence is it
513A - Game